package com.cyz.controller;

import com.cyz.annotation.AuthCheck;
import com.cyz.common.BaseResponse;
import com.cyz.common.ResultUtils;
import com.cyz.constant.UserConstant;
import com.cyz.exception.BusinessException;
import com.cyz.exception.ErrorCode;
import com.cyz.manager.CosManager;
import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.COSObjectInputStream;
import com.qcloud.cos.utils.IOUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

@Slf4j
@RestController
@RequestMapping("/file")
public class FileController {

    @Resource
    CosManager cosManager;


    /**
     * 测试文件上传
     *
     * @param multipartFile 前端传来的文件
     * @return  上传成功后的url链接
     */
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @PostMapping("/test/upload")
    public BaseResponse<String> testUploadFile(@RequestPart("file") MultipartFile multipartFile) {
        // 文件目录
        String filename = multipartFile.getOriginalFilename();
        String filepath = String.format("/test/%s", filename);
        File file = null;
        try {
            // 上传文件
            file = File.createTempFile(filepath, null);
            multipartFile.transferTo(file);
            cosManager.putObject(filepath, file);
            // 返回可访问地址
            return ResultUtils.success(filepath);
        } catch (Exception e) {
            log.error("file upload error, filepath = " + filepath, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
        } finally {
            if (file != null) {
                // 删除临时文件
                boolean delete = file.delete();
                if (!delete) {
                    log.error("file delete error, filepath = {}", filepath);
                }
            }
        }
    }


    /**
     * 测试文件下载
     *
     * @param filePath 文件路径
     * @param response 响应对象
     */
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @PostMapping("/test/download")
    public void download(String filePath, HttpServletResponse response) throws IOException {
        COSObjectInputStream objectContent = null;
        try {

            // 从云端获取文件对象
            COSObject cosObject = cosManager.getObject(filePath);
            // 从对象中获取文件流
            objectContent = cosObject.getObjectContent();

            // 将文件流转换成字节类型
            byte[] bytes = IOUtils.toByteArray(objectContent);
            // 设置响应头
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + filePath);

            // 将文件流写入响应体
            response.getOutputStream().write(bytes);
            response.getOutputStream().flush();

        } catch (IOException e) {
            log.info("文件下载失败,filePath = {}", filePath, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "下载失败");
        } finally {
            // 关闭流
            if (objectContent != null) {
                objectContent.close();
            }
        }
    }
}



